#include "button_driver.h"
#include "driver/gpio.h"
#include "mcu_io_config.h"

#define ESP_INTR_FLAG_DEFAULT 0

TaskHandle_t button_scanf_task_handle;
QueueHandle_t button_isr_quene_handle;
QueueHandle_t button_event_quene_handle;

TimerHandle_t Up_button_timer_handle;//软件定时器句柄
TimerHandle_t Down_button_timer_handle;
TimerHandle_t Enter_button_timer_handle;

bool up_flag = 0;
bool down_flag = 0;
bool enter_flag = 0;

static void IRAM_ATTR gpio_isr_handler(void* arg)
{
    button_msg_t button_msg;
    button_msg.num = (uint32_t) arg;;
    button_msg.level =  gpio_get_level(button_msg.num);
    xQueueSendFromISR(button_isr_quene_handle, &button_msg, NULL);
}

void button_softTimer_callback(void* xTimer)
{
    TimerHandle_t timer = (TimerHandle_t)xTimer;
    int ID = (int) pvTimerGetTimerID( timer );
    switch (ID)
    {
    case UP_Pin:
        up_flag = 0;
        break;
    case DOWN_Pin:
        down_flag = 0;
        break;
    case ENTER_Pin:
        enter_flag = 0;
        break;
    default:
        break;
    }
}

esp_err_t ESP_button_GPIO_init(void)
{

    esp_err_t ret;
    gpio_config_t io_conf;
    //interrupt of rising edge
    io_conf.intr_type = GPIO_INTR_POSEDGE;
    //bit mask of the pins, use GPIO4/5 here
    io_conf.pin_bit_mask = ((1 << UP_Pin) | (1 << DOWN_Pin) | (1 << ENTER_Pin));
    //set as input mode
    io_conf.mode = GPIO_MODE_INPUT;
    //enable pull-up mode
    io_conf.pull_up_en = GPIO_PULLUP_DISABLE;
    io_conf.pull_down_en = GPIO_PULLDOWN_ENABLE;
    ret = gpio_config(&io_conf);

    //install gpio isr service
    ret = gpio_install_isr_service(ESP_INTR_FLAG_DEFAULT);
    //hook isr handler for specific gpio pin
    ret = gpio_isr_handler_add(DOWN_Pin, gpio_isr_handler, (void*) DOWN_Pin);
    //hook isr handler for specific gpio pin
    ret = gpio_isr_handler_add(UP_Pin, gpio_isr_handler, (void*) UP_Pin);
    //hook isr handler for specific gpio pin
    ret = gpio_isr_handler_add(ENTER_Pin, gpio_isr_handler, (void*) ENTER_Pin);

    return ret;
}